/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */

#include "M2SkinFile.h"

namespace GNgine
{
	M2SkinFile::~M2SkinFile(void)
	{
		if(_buf){
			delete _buf;
		}
	}

	M2SkinFile::M2SkinFile(GFile *f)
		: _file(f),_buf(0),_header(0),_ok(false),
		_nIndices(0),_indices(0),_subMeshes(0),_textUnits(0)
	{
		assert(_file);


		int size=_file->getSize();
		_buf=new char[size];
		_file->read(_buf,size);

		parse();
	}

	bool M2SkinFile::parse()
	{
		
		_header=(M2SkinHeader*)(_buf);
		
		if(strncmp(_header->id,"SKIN",4)!=0){
			_ok=false;
			return false;
		}


		unsigned short *lookup = (unsigned short*)(_buf + _header->ofsIndices);
		unsigned short *tris = (unsigned short*)(_buf + _header->ofsTris);

		_nIndices = _header->nTris;// triangle index count (actual triangle * 3)
		_indices = new unsigned short[_nIndices];
		for (int i = 0; i<_nIndices; i++) {
			_indices[i] = lookup[tris[i]];
		}
		
		_subMeshes=(M2SubMesh*)(_buf+_header->ofsSub);
		_textUnits=(M2TexUnit*)(_buf+_header->ofsTex);

		_ok=true;
		return true;
	}

}
